package utils

import (
	"crypto/rand"
	"encoding/hex"
	"errors"
	"time"
	
	"github.com/golang-jwt/jwt/v5"
	"less_day/internal/config"
)

type JWTClaims struct {
	UserID uint   `json:"user_id"`
	OpenID string `json:"openid"`
	jwt.RegisteredClaims
}

func GenerateToken(userID uint, openID string) (string, error) {
	cfg, err := config.LoadConfig()
	if err != nil {
		return "", err
	}
	
	claims := JWTClaims{
		UserID: userID,
		OpenID: openID,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(cfg.JWT.Expire) * time.Second)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    "less_day",
		},
	}
	
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(cfg.JWT.Secret))
}

func ParseToken(tokenString string) (*JWTClaims, error) {
	cfg, err := config.LoadConfig()
	if err != nil {
		return nil, err
	}
	
	token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(cfg.JWT.Secret), nil
	})
	
	if err != nil {
		return nil, err
	}
	
	if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
		return claims, nil
	}
	
	return nil, errors.New("invalid token")
}

func GenerateRandomString(length int) (string, error) {
	bytes := make([]byte, length)
	if _, err := rand.Read(bytes); err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}